/*
 * ================================================================================变量定义区
 */
var showCount = 10; // 定义每页显示条数
var currentPage = 1; // 全局变量，当前页
var treeNode; // 组织机构树节点
var survey_id = parent.survey_id; // 接收父页面传递的问卷编号
/*
 * ================================================================================页面初始化函数
 */
$(function() {
	// 加载数
	departmentTree();
});

/*
 * ================================================================================函数定义区
 * 
 */
/**
 * 判断初始化时父节点checkbox的状态
 */
function checkedParent(){
	var zTreeObj = $.fn.zTree.getZTreeObj("departmentTree");
	var nodes = zTreeObj.getCheckedNodes();
	for (var i = 0, l = nodes.length; i < l; i++) {
		zTreeObj.checkNode(nodes[i], true, true);
	}
}


/**
 * 加载树和树的点击事件
 * 
 * @param title
 */
function departmentTree() {
	var setting = {
		check : {
			enable : true,
			chkStyle : "checkbox",
			chkboxType : {
				"Y" : "ps",
				"N" : "ps"
			}
		},
		data : {
			key : {
				title : "titleTip"
			},
			simpleData : {
				enable : true
			}
		},
		callback : {
			onClick : showDepartmentUsers,
			onCheck : zTreeOnCheck
		}
	};

	var zNodes = '[';

	$.ajax(
			{
				type : 'POST',
				url : BASE_PATH
						+ '/survey/surveyManagement/surveyRelease/queryDepartmentListBySurveyId.do',
				dataType : "json",
				data : {
					"surveyId" : survey_id,
				},

				success : function(data, textStatus) {
					for (var i = 0; i < data.length; i++) {
						zNodes += '{id:"' + convertSpecialChar(data[i].deptId) + '",';
						if (data[i].checkStatus == 'A') {
							
							zNodes += 'checked:' + true + ",";
							zNodes += 'halfCheck:' + false + ",";
						} else if (data[i].checkStatus == 'H') {
							zNodes += 'checked:' + false + ",";
							zNodes += 'halfCheck:' + true + ",";
						} else if (data[i].checkStatus == 'N') {
							zNodes += 'checked:' + false + ",";
							zNodes += 'halfCheck:' + false + ",";
						}
						zNodes += 'pId:' + data[i].parentId + ',';
						zNodes += 'name:"'
								+ convertSpecialChar(data[i].deptName) + '",';
						zNodes += 'titleTip:"'
								+ convertSpecialChar(data[i].deptName) + '",';

						if (data[i].deptDesc == null) {
							zNodes += 'deptDesc:"",';
						} else {
							zNodes += 'deptDesc:"'
									+ convertSpecialChar(data[i].deptDesc)
									+ '",';
						}
						zNodes += 'isLeaf:"' + data[i].isLeaf + '",';
						zNodes += 'open:true}';

						if (i != (data.length - 1)) {
							zNodes += ',';
						}
					}
					zNodes += ']';
					// 加载数
					$.fn.zTree
							.init($("#departmentTree"), setting, eval(zNodes));

					$("#departmentTree_1_a").trigger("click");
					checkedParent();
				},

				error : function(e) {
					openAlert("加载数据错误！");
					return;
				}
			});
}

var halfChange = new Array();
var treeNodes = new Array();
/**
 * 初始化时，若checkbox为半选状态，点击checkbox半选改为全选或不选
 * 
 * @param event
 * @param treeId
 * @param treeNode
 */
function zTreeOnCheck(event, treeId, treeNode) {
	var treeObj = $.fn.zTree.getZTreeObj("departmentTree");
	var changedNodes = treeObj.getChangeCheckedNodes();
	var halfCheckId = "";
	var treeNode;
	
	for (var i = 0; i < changedNodes.length; i++) {
		treeNode = changedNodes[i];
		halfCheckId = treeNode.id;
		if (treeNode.halfCheck == true && treeNode.checked == true) {//是半选并且被选中
			treeNode.halfCheck = false;
			treeNodes.push(uniqueArray(treeNode));
			halfChange.push(uniqueArray(halfCheckId));
		} 
	}
}

/**
 * 点击树节点展示树下所有用户信息
 * 
 * @param event
 * @param treeId
 * @param treeNode
 * @param clickFlag
 */
function showDepartmentUsers(event, treeId, tempTreeNode, clickFlag) {
	// 切换节点 ，都从第一页开始
	currentPage = 1;

	// 全局变量赋予树节点ID
	treeNode = tempTreeNode;

	// 初始化列表，取第一页数据
	getDataList(currentPage);
}

/**
 * 获取列表数据
 * 
 * @param currentPage
 *            请求的页码
 * @param deptId
 *            部门号
 * @param surveyId
 *            调查问卷的编号
 */
function getDataList(pageIndex) {
	$.ajax({
				type : 'POST',
				url : BASE_PATH+ '/departmentManagement/queryUsersInDepartment.do',
				dataType : "json",
				data : {
					"showCount" : showCount,
					"currentPage" : pageIndex,
					"deptId" : treeNode.id,
					"surveyId" : survey_id,
					"type" : 1,
					"query_condition_field_list" : "surveyId,deptId,type"
				},
				cache : false,

				success : function(data, textStatus) {
					var html = "";
					var pageData = data;
					var totalResult = pageData.queryParam.totalResult;

					if (pageData.queryResult != null) {
						   // 解析data, 组装成html
						   $.each(
										pageData.queryResult,
										function(i, n) {
											html += '<tr id="tr_index_'
													+ i
													+ '">'
													+ '<td style="text-align:center;" title='
													+ n.is_join
													+ '>'
													+ n.is_join
													+ '</td>'
													+ '<td title='
													+ switcHtml(n.username)
													+ '>'
													+ switcHtml(n.username)
													+ '</td>'
													+ '<td title='
													+ switcHtml(check(n.cn_name))
													+ '>'
													+ switcHtml(check(n.cn_name))
													+ '</td>'
													+ '<td title='
													+ switcHtml(check(n.dept_name))
													+ '>'
													+ switcHtml(check(n.dept_name))
													+ '</td>'
													+ '<td style="width: 1px;"></td>'
													+ '</tr>';
										});
					} else {
						html = '<tr><td colspan="2">No items.</td></tr>';
					}

					$('#tBodyList').html(html);
					currentPage = pageIndex;

					if (totalResult == 0) {
						$('#tBodyList')
								.html(
										'<tr><td style="text-align:center;">No items.</td></tr>');

						// 没有记录的时候，隐藏分页插件
						$("#pagination").hide();
					} else {
						// 创建分页
						$("#pagination").show();
						$("#pagination").pagination(totalResult, {
							num_edge_entries : 1, // 边缘页数
							num_display_entries : 3, // 主体页数
							current_page : currentPage,
							callback : getDataList,
							items_per_page : showCount
						// 每页显示1项
						});
					}
					;
				},

				error : function(e) {
					openAlert("加载数据错误！");
					return;
				}
			});
}
//去除数组中重复元素
function uniqueArray(data){  
	data = data || [];  
   var a = {};  
   for (var i=0; i<data.length; i++) {  
       var v = data[i];  
       if (typeof(a[v]) == 'undefined'){  
            a[v] = 1;  
       }  
   };  
   data.length=0;  
   for (var i in a){  
        data[data.length] = i;  
   }  
   return data; 
}  

function submittUser() {
	// 判断checkbox为选中状态的部门
	var treeObj = $.fn.zTree.getZTreeObj("departmentTree");
	var nodes = treeObj.getChangeCheckedNodes();
	var checkedDeptIds = "";
	var nocheckedDeptIds = "";
	var nocheckedDeptIds1 = "";
	var halfCheckIds = "";

	for (var i = 0; i < nodes.length; i++) {
		if (nodes[i].isParent == false) { // 判断该节点是否为叶子节点
			if (nodes[i].checked == true) {
				var checkedDeptId = nodes[i].id; // checked false--->true
				checkedDeptIds += checkedDeptId + ",";
			} else if (nodes[i].checked == false) {
				var nocheckedDeptId = nodes[i].id;// checked true--->false
				nocheckedDeptIds1 += nocheckedDeptId + ",";
			}
		}
	}
	

	for(var i = 0 ; i < treeNodes.length ; i++){
		if(treeNodes[i].checked == false){
			halfCheckIds += halfChange[i] + ",";
		}
	}
	nocheckedDeptIds = nocheckedDeptIds1 + halfCheckIds;

	if (nocheckedDeptIds == "" && checkedDeptIds == "") {
		openAlert('没有需要更改的内容');
	}

	   $.ajax({
				type : 'POST',
				url : BASE_PATH
						+ '/survey/surveyManagement/surveyRelease/submitCheckedUser.do',
				dataType : "json",
				data : {
					"checkedDeptIds" : checkedDeptIds,
					"nocheckedDeptIds" : nocheckedDeptIds,
					"surveyId" : survey_id,
				},

				success : function(data) {
					if (data == 'success') {
						openAlert('更改成功');

						// 刷新当前页
						getDataList(currentPage);
						departmentTree();

						// 清空之前的记录信息
						chooseIds = new Array();
						halfChange = new Array();
						treeNodes = new Array();
						
					} else {
						openAlert('更改失败');

						// 清空之前的记录信息
						chooseIds = new Array();
						halfChange = new Array();
						treeNodes = new Array();
					}
				},

				error : function(e) {
					openAlert("加载数据错误！");
				}
			});

}


/**
 * 判断是否为空
 * 
 * @param name
 * @returns
 */
function check(name) {
	if (name == null) {
		return name = '';
	} else {
		return name;
	}
}


